package cn.ren.cloud.mq.consumer;

import cn.ren.cloud.domain.Course;
import cn.ren.cloud.domain.MessageSms;
import cn.ren.cloud.domain.User;
import cn.ren.cloud.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 23508
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "course-group", topic = "course-topic", selectorExpression = "course-tag")
public class CourseConsumer implements RocketMQListener<MessageExt> {

    private final IMessageSmsService messageSmsService;

    public CourseConsumer(IMessageSmsService messageSmsService) {
        this.messageSmsService = messageSmsService;
    }

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0) {
            log.error("课程消息为空");
            return;
        }
        String str = new String(body, StandardCharsets.UTF_8);
        Course course = JSON.parseObject(str, Course.class);
        String message = "亲爱的用户您好，最新课程 <a href='localhost:6002/detail.html?courseId=" + course.getId() + "'> " + course.getName() + " </a> 发布啦，点击课程了解详情";
        List<User> users = Arrays.asList(new User(1L, "13548157513"),
                new User(2L, "19999998888"),
                new User(3L, "19999997777")
        );
        users.forEach(e -> {
            log.info(message + ":" + e.getId());
            // 2.保存发送日志到数据库
            MessageSms messageSms = new MessageSms();
            messageSms.setTitle("课程发布");
            messageSms.setContent(message);
            messageSms.setSendTime(new Date());
            messageSms.setUserId(e.getId());
            messageSmsService.insert(messageSms);
        });
    }
}
